package com.cq.hd.admin.controller;

import com.cq.hd.admin.dto.AdminUserCreateDto;
import com.cq.hd.admin.annotation.RequiresPermissionsDesc;
import com.cq.hd.admin.dto.AdminUserDto;
import com.cq.hd.admin.dto.AdminUserUpdateDto;
import com.cq.hd.admin.dto.UpdatePasswordDto;
import com.cq.hd.admin.po.TbAdminUserPo;
import com.cq.hd.admin.service.TbAdminUserService;
import com.cq.hd.admin.utils.RegexUtil;
import com.cq.hd.admin.utils.StringUtil;
import com.cq.hd.admin.vo.AdminUserDetailVo;
import com.cq.hd.admin.vo.UpdatePasswordPreDto;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.enums.biz.SmsTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.ResultGenerator;
import com.cq.hd.member.api.SmsApi;
import com.cq.hd.member.api.dto.SmsVerifyDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mYunYu
 * @since 2021-10-28
 */

@Api(tags = "管理员信息相关接口")
@Slf4j
@RestController
@RequestMapping("/admin/user")
public class TbAdminUserController extends BaseController {

    private TbAdminUserService adminUserService;

    @Autowired
    public void setAdminUserService(TbAdminUserService adminUserService) {
        this.adminUserService = adminUserService;
    }

    @Autowired
    private SmsApi smsApi;

    @ApiOperation(value = "用户信息详情列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "userRole", value = "用户角色", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query", dataType = "int")
    })
    @GetMapping("/list/more")
    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "查询")
    public Object listMore(String userName, String userRole,
                           @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<AdminUserDetailVo> pageResult = adminUserService.getAdminUserList(userName, userRole, pageNum, pageSize);
        return ResultGenerator.success(pageResult);
    }

    @ApiOperation(value = "新增管理员")
    @PostMapping("/create")
    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "添加")
    public Object create(@RequestBody AdminUserCreateDto adminUserCreateDto) {
        String userName = adminUserCreateDto.getUserName();
        String password = adminUserCreateDto.getPassword();
        if (StringUtils.isEmpty(userName)) {
            return ResultGenerator.error("参数异常");
        }
        if (!RegexUtil.isUsername(userName)) {
            return ResultGenerator.error("管理员名称不符合规定");
        }
        if (StringUtils.isEmpty(password) || password.length() < 6) {
            return ResultGenerator.error("管理员密码长度不能小于6");
        }

        TbAdminUserPo adminUser = adminUserService.getUserByUserName(userName);
        if (adminUser != null) {
            return ResultGenerator.error("管理员已经存在");
        }
        String rawPassword = adminUserCreateDto.getPassword();
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        String encodedPassword = encoder.encode(rawPassword);
        String encodedPassword = StringUtil.SHA1(userName + password);
        adminUserCreateDto.setPassword(encodedPassword);

        AdminUserDto adminUserDto = new AdminUserDto();
        BeanUtils.copyProperties(adminUserCreateDto, adminUserDto);

        adminUserService.addAdminUser(adminUserDto);
        return ResultGenerator.success(adminUserDto);
    }

    @ApiOperation(value = "删除管理员")
    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "删除")
    @PostMapping("/delete/{id}")
    public Object delete(@PathVariable("id") Integer id) {
        if (id == null) {
            return ResultGenerator.error("参数异常");
        }

        // 管理员不能删除自身账号
        TbAdminUserPo currentUser = getCurrentUser();
        if (currentUser.getId().equals(id)) {
            return ResultGenerator.error("管理员不能删除自己账号");
        }
        adminUserService.deleteAdminUser(id);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "编辑管理员")
    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu = {"系统管理", "管理员管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody AdminUserUpdateDto adminUserUpdateDto) {
        Integer anotherAdminId = adminUserUpdateDto.getId();
        if (anotherAdminId == null) {
            return ResultGenerator.error("参数异常");
        }
        // 不允许管理员通过编辑接口修改密码
//        adminUserVo.setPassword(null);

        AdminUserDto adminUserDto = new AdminUserDto();
        BeanUtils.copyProperties(adminUserUpdateDto, adminUserDto);

        adminUserService.updateAdminUserById(adminUserDto);

        return ResultGenerator.success(adminUserDto);
    }

    @ApiOperation(value = "编辑头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "avatar", value = "用户头像", paramType = "query", dataType = "String")
    })
    @PostMapping("/updateAvatar")
    public Object updateAvatar(String avatar) {
        if (StringUtils.isEmpty(avatar)) {
            return ResultGenerator.success();
        }
        TbAdminUserPo adminUserVo = getCurrentUser();
        adminUserService.updateAvatarById(avatar, adminUserVo.getId());

        return ResultGenerator.success();
    }


    @ApiOperation(value = "修改密码初始数据")
    @RequiresAuthentication
    @GetMapping("/prePassword")
    public Object prePassword() {
        TbAdminUserPo adminUserVo = getCurrentUser();

        UpdatePasswordPreDto updatePasswordPreDto = new UpdatePasswordPreDto();
        updatePasswordPreDto.setFirstSetPwdState(StringUtils.isEmpty(adminUserVo.getPassword()));
        updatePasswordPreDto.setBusinessState(adminUserVo.getRoleId() != null && adminUserVo.getRoleId().equals(Constant.BUSINESS_ROLE_ID));
        updatePasswordPreDto.setMobile(adminUserVo.getMobile());

        return ResultGenerator.success(updatePasswordPreDto);
    }

    @ApiOperation(value = "管理员密码修改")
    @RequiresAuthentication
    @PostMapping("/password")
    public Object create(@RequestBody UpdatePasswordDto updatePasswordDto) {
        String oldPassword = updatePasswordDto.getOldPassword();
        String newPassword = updatePasswordDto.getNewPassword();
        String confirmNewPassword = updatePasswordDto.getConfirmNewPassword();

        if (StringUtils.isEmpty(newPassword)) {
            return ResultGenerator.error("请输入新密码");
        }

        if (StringUtils.isEmpty(confirmNewPassword)) {
            return ResultGenerator.error("请输入确认新密码");
        }

        if (!newPassword.equals(confirmNewPassword)) {
            return ResultGenerator.error("两次输入的密码不一致");
        }

        if (!validatePassword(newPassword)) {
            return ResultGenerator.error("请输入8-16位，包含字母、数字的密码");
        }

        TbAdminUserPo adminUserVo = getCurrentUser();
        String password = adminUserVo.getPassword();
        Integer roleId = adminUserVo.getRoleId();

        if (!StringUtils.isEmpty(password)) {
            // 非首次设置,需填写旧密码
            if (StringUtils.isEmpty(oldPassword)) {
                return ResultGenerator.error("请输入旧密码");
            }

            String oldEncodedPassword = StringUtil.SHA1(adminUserVo.getUserName() + oldPassword);
            if (StringUtils.isEmpty(oldEncodedPassword) || !oldEncodedPassword.equals(password)) {
                return ResultGenerator.error("账号密码不对");
            }
        }

        if (roleId != null && roleId.equals(Constant.BUSINESS_ROLE_ID)) {
            // 如果是商家角色,则需要校验短信验证码
            String smsCode = updatePasswordDto.getSmsCode();
            if (StringUtils.isEmpty(smsCode)) {
                return ResultGenerator.error("验证码不能为空");
            }

            String mobile = adminUserVo.getMobile();
            if (StringUtils.isEmpty(mobile)) {
                return ResultGenerator.error("密码修改失败,手机号为空,请联系客服");
            }

            // 判断短信验证码是否正确
            SmsVerifyDto smsVerifyDto = new SmsVerifyDto();
            smsVerifyDto.setCode(smsCode);
            smsVerifyDto.setMobile(mobile);
            smsVerifyDto.setType(SmsTypeEnum.SMS_UPDATE_BUSINESS_ADMIN_LOGIN_PWD.getValue());
            smsApi.verify(smsVerifyDto).isSuccess();
        }

        adminUserVo.setPassword(StringUtil.SHA1(adminUserVo.getUserName() + newPassword));
        adminUserVo.setUpdateTime(LocalDateTime.now());
        adminUserService.updateById(adminUserVo);
        return ResultGenerator.success();
    }

    public static boolean validatePassword(String password) {
        String regex = "^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z\\d]{8,16}$";
        return Pattern.compile(regex).matcher(password).matches();
    }

    public static void main(String[] args) {
        String userName = "mYunYu";
        String password = "123456";
        String encodedPassword = StringUtil.SHA1(userName + password);
        System.out.println(encodedPassword);
    }

}
